package com.shiyo.spring.basic_dl.e_lazylookup;

import com.shiyo.spring.basic_dl.e_lazylookup.bean.Cat;
import com.shiyo.spring.basic_dl.e_lazylookup.bean.Dog;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class LazyLookUpApplication {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("basic_dl/quickstart-lazylookup.xml");
        Cat cat = (Cat) context.getBean("cat");
        try{
            // No bean named 'dog' available
            Dog dog = (Dog) context.getBean("dog");
        }catch (NoSuchBeanDefinitionException e){
            System.out.println("No bean named 'dog' available");
        }


        ObjectProvider<Dog> dogProvider = context.getBeanProvider(Dog.class);
//        Dog dog = dogProvider.getIfAvailable();
//        if (dog != null) {
//            System.out.println(dog);
//        }else {
//            Dog dog1 = new Dog();
//            System.out.println(dog1);
//        }

        //找不到bean时直接使用Supplier接口返回默认实现
        Dog dog1 = dogProvider.getIfAvailable(() -> new Dog());
        System.out.println("new dog>>>" + dog1);

        //对可用得bean拿出来直接使用
        // 注意这个实例并不会被注册到Spring容器中，因此ifAvailable仍然检测不到Bean，导致没有输出
        dogProvider.ifAvailable(System.out::println);
    }
}
